<template>
  <div class="container">
    <div class="main">
      <div style="padding:10px 0;">
        <div style="padding:15px;border:1px solid #eee;">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item :to="{ path: pageType==2?'/resourceUpload':(pageType==3?'/homeSearch':'/resourceList') }">{{pageType==2?'媒资上传':(pageType==3?'首页':'媒资搜索')}}</el-breadcrumb-item>
                <el-breadcrumb-item>{{fileDetail.title}}</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
    </div>
      <div style="padding:10px;" v-if="pageType == 2">
        <el-button type="primary" size="medium" icon="el-icon-upload2" @click="handleUpload()" v-if="roulShowList.btn2.type">添加资源</el-button>
        <el-button type="danger" size="medium" icon="el-icon-delete" @click="delAllSelection" v-if="roulShowList.btn1.type">批量删除</el-button>
      </div>
      <div class="scrollbar" style="height:82vh;">
        <div class="traingplan">
          <dl v-for="(item, index) in tableData" :key="index" class="traingplan-group">
            <dt style="position:relative;">
              <span class="traingplan-checkbox" v-if="pageType == 2 && roulShowList.btn1.type"><el-checkbox v-model="item.checked" @change="(e)=>selectDel(index,e)"></el-checkbox></span>
              <div class="traingplan-img-group" @click="goToDetail(item)" v-if="item.cover_image">
                <img style="filter: blur(15px);z-index:2" :src="item.cover_image" />
                <img style="z-index:3; object-fit:contain" :src="item.cover_image" />
              </div>
              <div class="traingplan-img-group" @click="goToDetail(item)" v-else>
                <img src="../../assets/img/mrt.png" />
              </div>
              <p style="display:flex;align-items: center;justify-content: space-between;padding:4px 10px;font-size:14px;color:#888;">
                <span>名称：{{item.title}}</span>
                <span>下载：{{item.download_num || 0}}</span>
              </p>
              <p style="display:flex;align-items: center;justify-content: flex-end;padding:4px 10px;">
                <el-button size="mini" type="primary" @click="handleDown(1,item)">下载</el-button>
                <span style="padding:8px;"></span>
                <el-button size="mini" type="primary" @click="handleViews(item,index)">预览</el-button>
                <span style="padding:8px;"></span>
                <el-popconfirm title="确定删除吗？" @confirm="handleDelete(item.id,item.title)" v-if="pageType == 2 && roulShowList.btn1.type">
                <el-button slot="reference" size="mini" type="danger">删除</el-button>
                </el-popconfirm>
              </p>
            </dt>
          </dl>
        </div>
        <not-find v-if="tableData.length==0"></not-find>
        <div class="pagination" v-if="tableData.length>0">
            <el-pagination
                layout="sizes,total, prev, pager, next, jumper"
                :current-page="query.pageIndex"
                :page-size="query.pageSize"
                :page-sizes="[8, 16, 32, 64, 128]"
                @size-change="handleSizeChange"
                :total="query.total"
                @current-change="handlePageChange"
            ></el-pagination>
        </div>
        <div class="detail-title">{{fileDetail.title}}</div>
        <div class="detail-text">{{fileDetail.content}}</div>
        <div class="detail-text">总下载次数:{{fileDetail.download_num  || 0}}<span style="margin-left:30px;"></span> 拍摄时间：{{fileDetail.shooting_time}}</div>
      </div>
    </div>
    <div class="main-left">
      <div class="main-left-top">
        <div class="main-list-group">
            <el-row :gutter="20">
                <el-col :span="6">
                    <div class="main-list-title">素材格式:</div>
                </el-col>
                <el-col :span="18">
                  <div class="main-list-res">{{fileDetail.file_type}}</div>
                </el-col>
            </el-row>
        </div>
        <div class="main-list-group">
            <el-row :gutter="20">
                <el-col :span="6">
                    <div class="main-list-title">素材大小:</div>
                </el-col>
                <el-col :span="18">
                  <div class="main-list-res">{{fileDetail.file_size}}</div>
                </el-col>
            </el-row>
        </div>
        <div class="main-list-group">
            <el-row :gutter="20">
                <el-col :span="6">
                    <div class="main-list-title">素材像素:</div>
                </el-col>
                <el-col :span="18">
                  <div class="main-list-res">{{fileDetail.file_info}}</div>
                </el-col>
            </el-row>
        </div>
      </div>
      <div class="main-left-bottom" style="border-top:1px dashed #eee;">
        <div class="main-list-group">
            <el-row :gutter="20">
                <el-col :span="6">
                    <div class="main-list-title">上传者:</div>
                </el-col>
                <el-col :span="18">
                  <div class="main-list-res">{{fileDetail.account}}</div>
                </el-col>
            </el-row>
        </div>
        <div class="main-list-group">
            <el-row :gutter="20">
                <el-col :span="6">
                    <div class="main-list-title">上传时间:</div>
                </el-col>
                <el-col :span="18">
                  <div class="main-list-res">{{fileDetail.create_time}}</div>
                </el-col>
            </el-row>
        </div>
        <div class="main-list-group">
            <el-row :gutter="20">
                <el-col :span="6">
                    <div class="main-list-title">标签:</div>
                </el-col>
                <el-col :span="18">
                  <div>
                    <el-button style="margin:0 10px 10px 0" size="small" v-for="(item,index) in category" :key="index" :class="[item.iswarn?'is-warn':'a']">{{item.title}}</el-button>
                  </div>
                </el-col>
            </el-row>
        </div>
        <p style="color:red;margin-top:30px;" v-if="categoryString">本素材包含敏感内容“{{categoryString}}”,使用时请注意分辨!</p>
        <div style="margin-top:30px;text-align:center;">
          <el-button type="danger" v-if="tableData.length>0 && fileDetail.type==0" @click="handleDown(2)">打包下载</el-button>
        </div>
      </div>
    </div>
    <el-image-viewer
            v-if="dialogVisible"
            :zIndex="9999"
            :on-close="()=>dialogVisible=false"
            :url-list="imgList"
            :initial-index="imgIndex"
        />
        <el-dialog title="视频" :visible.sync="dialog" width="50%" top="10%" :before-close="originaClose">
          <video :src="originalVideo" autoplay controls style="width:100%;height:500px;" ref="originaVideo"></video>
        </el-dialog>
  </div>
</template>
<script>
import bus from '@/common/bus';
import notFind from "@/view/common/notFind";
import ElImageViewer from "element-ui/packages/image/src/image-viewer";
export default {
  name: "resourceEdit",
  components:{notFind,ElImageViewer},
  data() {
    return {
      category: [],
      imgIndex:0,
      imgList: [],
      categoryString: null,
      tableData: [],
      keyword:'',
      fileType:'',
      dialogVisible: false,
      finished: false,
      error: false,
      query: {
        pageIndex: 1,
        pageSize: 8,
        total:0
      },
      page: 1,
      dialog: false,
      originalVideo:'',
      imgPath: this.$API.CrmImagesUrl,
      fileDetail:{},
      pageType:1,
      roulShowList: {
          btn1: { rule: 'homepage,upload,media_file_del', type: false, name: '删除' },
          btn2: { rule: 'homepage,upload,upload', type: false, name: '上传' }
      },
    };
  },
  created() {
    this.media_id=this.$route.query.id
    this.pageType=this.$route.query.type
    this.initAjaxMethod();
    this.roleMethod();
    // 如果有添加成功的需要重新加载
    bus.$on('media-change', () => {
      console.log('重新加载了')
       this.initAjaxMethod();
    });
  },
  methods: {
    selectDel(index,checked){
      this.tableData[index].checked=checked;
    },
    handleViews(data,index){
      if(this.fileDetail.type == 0){
        this.dialogVisible=true;
        this.imgIndex=index;
      }else if(this.fileDetail.type == 1){
        this.originalVideo=data.compress_file_path || data.file_path;
			  this.dialog=true;
      }
    },
		originaClose(done){
			this.$refs['originaVideo'].pause();
			done();
		},
    handleSizeChange(val) {
      this.query.pageSize=val;
      this.initAjaxMethod();
    },
    handlePageChange(val){
      this.query.pageIndex=val;
      this.initAjaxMethod();
    },
    handleUpload(){
      let isUploadlist=window.sessionStorage.getItem('uploadResuolute');
      if(isUploadlist){
        isUploadlist=JSON.parse(isUploadlist);
        let isUploadStatus=true;
        for(const i in isUploadlist){
          if(isUploadlist[i] == 'error'){
            isUploadStatus='error';
            break;
          }
          if(isUploadlist[i] != 'error' && isUploadlist[i] != 'success'){
            isUploadStatus='load';
            break;
          }
        }

        if(isUploadStatus == 'error' || isUploadStatus == 'load'){
          const content=isUploadStatus == 'load'?'有资源正在上传中,请稍后重试！':'有资源上传失败,是否继续上传操作？稍后可在上传记录中重新操作！'
          this.$confirm(content, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
                if(isUploadStatus == 'error'){
                  bus.$emit('global-uploader-open', true,{...this.fileDetail,media_id:this.media_id});
                  window.sessionStorage.removeItem('uploadResuolute');
                }
            }).catch(err=>{})
        }else{
          bus.$emit('global-uploader-open', true,{...this.fileDetail,media_id:this.media_id});
          window.sessionStorage.removeItem('uploadResuolute');
        }
      }else{
        bus.$emit('global-uploader-open', true,{...this.fileDetail,media_id:this.media_id});
      }
      
    },
    handleDown(flag,item=null){
      const url=flag == 1?this.$API.MEDIA_ALONE_DOWN:this.$API.MEDIA_ALl_DOWN;
      const data=flag == 1?{media_file_id:item.id}:{media_id:this.media_id}
      const loading = this.$loading({ text: "加载中..." });
      this.$http
        .post(url,data)
        .then((res) => {
          if (res.code == 1 && res.data && res.data.download_url) {
            const fileType=res.data.download_url.substring(res.data.download_url.lastIndexOf('.'));  
            const fileName=(flag == 1?item.title:this.fileDetail.title)+fileType;
            var nowA =document.createElement('a');
            nowA.setAttribute('href',res.data.download_url);
            nowA.setAttribute('download',fileName);
            nowA.style.display= 'none';
            document.body.appendChild(nowA);
            nowA.click();
            document.body.removeChild(nowA);
          } else {
            let msg=res.msg?res.msg:'下载失败';
            this.$message.error(msg);
          }
          loading.close();
        })
        .catch((err) => {
          loading.close();
          this.$message.error(err.msg);
        });
    },
    delAllSelection() {
      let dels=[],detail=[];
      this.tableData.forEach(item=>{
        if(item.checked){
          dels.push(item.id);
          detail.push(item.title);
        }
      })
      if(dels.length<=0){
        return this.$message.error('请选择一个目录');
      }
      this.$confirm("确定要删除吗？", "提示", {
        type: "warning",
      })
        .then(() => {
          this.handleDelete(dels.join(","),detail.join(','));
        })
        .catch(() => {});
    },
    handleDelete(id,detail){
      const loading = this.$loading({ text: "加载中..." });
      this.$http
        .post(this.$API.MEDIA_FILE_DEL, { ids: id,detail:detail})
        .then((res) => {
          loading.close();
          console.log("公海列表", res);
          if (res.code == 1) {
            this.$message.success("删除成功");
            this.initAjaxMethod();
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((err) => {
          this.$message.error(err.msg);
        });
    },
    initAjaxMethod() {
        this.$http.post(this.$API.MEDIA_DETAIL, {
          page: this.query.pageIndex,
          listRows: this.query.pageSize,
          media_id:this.media_id
        })
        .then((res) => {
          if (res.code == 1) {
            let list = Array.isArray(res.data.file_list.data) ? res.data.file_list.data : [];
            let category = Array.isArray(res.data.detail.category) ? res.data.detail.category : [];
            let categoryArr=[]
            category.forEach(item=>{
              if(item.iswarn == 1){
                categoryArr.push(item.title)
              }
            })
            list.forEach(item=>{
              item.checked=false;
            })
            this.tableData = list;
            if(res.data.detail.type == 0){
              this.imgList=list.map(item=>(item.compress_file_path || item.file_path))
            }
            this.query.total=res.data.file_list.total;
            this.fileDetail=res.data.detail;
            this.categoryString=categoryArr.length>0?categoryArr.join('、'):null;
            this.category=category;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((err) => {
          this.$message.error(err.msg);
        });
    },
    roleMethod(){
      this.$http.post(this.$API.GET_TRR_PAGE, { rule: 'homepage,upload' }).then((res) => {
            console.log('页面权限', res);
            if (res.data === 'admin') {
                for (let i in this.roulShowList) {
                    this.roulShowList[i].type = true;
                }
            } else {
                res.data.forEach((item) => {
                    for (let j in this.roulShowList) {
                        if (item.rule == this.roulShowList[j].rule) {
                            this.roulShowList[j].type = true;
                        }
                    }
                });
            }
        });
    }
  },
  beforeDestroy(){
    window.sessionStorage.removeItem('jqjtIsBack');
  }
};
</script>
<style lang="less" scoped>
.container{
  display: flex;
  height: 100%;
  .main{
    width: 70%;
    height: 100%;
    background: #fafafa;
    padding:20px;
  }
  .main-left{
    width:30%;
    height:100%;
    padding:20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .main-left-top{
      padding:20px;
      width:100%;
    }
    .main-left-bottom{
      padding:20px;
      width:100%;
    }
    .main-list-group{
      padding:6px 0;
      .main-list-title{
        font-size: 15px;
        color:#333;
        font-weight: bold;
        height: 24px;
        line-height: 24px;
        min-width: 90px;
        white-space: nowrap;
      }
      .main-list-res{
        font-size: 14px;
        color:#444;
        height: 24px;
        line-height: 24px;
      }
    }
  }
  .detail-title{
    font-size: 20px;
    font-weight: bold;
    color:#333;
  }
  .detail-text{
    font-size: 16px;
    line-height: 30px;
    color:#333;
    margin-top:10px;
  }
}
.traingplan {
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
}
.traingplan .traingplan-group {
  width: 25%;
  padding:10px;
  box-sizing: border-box;
  min-width:235px;
}
.traingplan dt {
  background: #ffffff;
  box-shadow: 0 12px 20px 0 rgba(0,0,0,.2);
  border-radius: 6px;
  overflow: hidden;
  font-size: 0;
}
.traingplan dt:hover{
  cursor: pointer;
  box-shadow:
   1px 1px 8px 4px rgba(0, 0, 0, 0.4);
}
.traingplan dl img {
  width: 100%;
  height:100%;
  position:absolute;
  top:0;
  left:0;
}
.traingplan-img-group{
  height: 160px;
  position:relative;
  overflow: hidden;
}
.traingplan dd {
  margin-top: 5px;
  font-size: 13px;
}
.is-warn{
  border:1px solid red!important;
}
.traingplan-checkbox{
  position:absolute;
  top:5px;
  left:5px;
  z-index:50;
}
</style>


